<%@ page contentType="text/html;charset=UTF-8" %>
<%@ include file="/WEB-INF/views/include/taglib.jsp"%>
<script type="text/javascript">
    $.fn.serializeObject = function(){
        var o = {};
        var a = this.serializeArray();
        $.each(a, function() {
            if (o[this.name]) {
                if (!o[this.name].push) {
                    o[this.name] = [o[this.name]];
                }
                o[this.name].push(this.value || '');
            } else {
                o[this.name] = this.value || '';
            }
        });
        return o;
    };

    function addrows(){
        if( $('#inputForm').parsley().validate()){
        if($('#quantityBad').val() == null || $('#quantityBad').val() == "" || typeof($('#quantityBad').val()) == "undefined"){
            toastr.error("请输入报损数量!");
            return ;
        }
        if(parseInt($('#quantityBad').val(),10) > parseInt($('#stockNum').val(),10)){
            toastr.error("报损出库数量太多,本库房该药品数量不够,请核实报损出库数量!");
            return ;
        }

        //出库金额总计
        var totalMoney = 0.00;
        var oldValue = $('#totalMoney').val();
        totalMoney = parseFloat(oldValue,10) + parseInt($('#quantityBad').val(),10) * parseFloat($('#retailPrice').val(),10);
            totalMoney = Math.round(parseFloat(totalMoney)* 100) / 100
        $('#totalMoney').val(totalMoney);

        var jsonuserinfo= $("#inputForm").serializeObject();
        var datastr = JSON.stringify(jsonuserinfo);
        var trHTML = "<tr>";
        trHTML += "<td hidden>"+datastr +"</td>";
        trHTML += "<td>"+$('#drugCode').val() +"</td>";
        trHTML += "<td>"+$('#drugName').val() +"</td>";
        trHTML += "<td>"+$('#packageNum').val() +"</td>";
        trHTML += "<td>"+$('#packageSpec').val() +"</td>";
        trHTML += "<td>"+$('#packageUnits').val() +"</td>";
        trHTML += "<td>"+$('#minSpec').val() +"</td>";
        trHTML += "<td>"+$('#minUnits').val() +"</td>";
        trHTML += "<td>"+$('#supplierName').val() +"</td>";
        trHTML += "<td>"+$('#purchasePrice').val() +"</td>";
        trHTML += "<td>"+$('#retailPrice').val() +"</td>";
//        trHTML += "<td>"+$('#discount').val() +"</td>";
        trHTML += "<td>"+$('#batchNo').val() +"</td>";
        trHTML += "<td>"+$('#expireDate2').val() +"</td>";
        trHTML += "<td>"+$('#quantityBad').val() +"</td>";
        trHTML += "<td>"+$('#stockNum').val() +"</td>";
        trHTML += "<td>"+$('#importDocumentNo').val() +"</td>";
        trHTML += "<td><a href='#' onclick='updateList(this)' class='btn btn-success btn-xs'>修改</a>"+"<a href='#' onclick='removeList(this)' class='applyBt btn btn-danger btn-xs'>删除</a></td>"
        trHTML += "</tr>";
        $("#inputForm input").val("");
        $("#contentTable").append(trHTML);
        return loadDiv('rigthCenterDiv','${ctx}/drug/drugExport/badForm');
    }
    }

    //表单自动回填的方法
    var fillForm = function($form, json) {
        var jsonObj = json;
        if (typeof json === 'string') {
            jsonObj = $.parseJSON(json);
        }
        for ( var key in jsonObj) { // 遍历json字符串
            var objtype = jsonObjType(jsonObj[key]); // 获取值类型
            if (objtype === "array") { // 如果是数组，一般都是数据库中多对多关系
                var obj1 = jsonObj[key];
                for ( var arraykey in obj1) {
                    // alert(arraykey + jsonObj[arraykey]);
                    var arrayobj = obj1[arraykey];
                    for ( var smallkey in arrayobj) {
                        setCkb(key, arrayobj[smallkey]);
                        break;
                    }
                }
            } else if (objtype === "object") { // 如果是对象，啥都不错，大多数情况下，会有 xxxId
                // 这样的字段作为外键表的id

            } else if (objtype === "string") { // 如果是字符串
                var str = jsonObj[key];
                var date = new Date(str);
                if (date.getDay()) { // 这种判断日期是本人懒，不想写代码了，大家慎用。
                    $("[name=" + key + "]", $form).val(str);
                    continue;
                }

                var tagobjs = $("[name=" + key + "]", $form);
                if ($(tagobjs[0]).attr("type") == "radio") {// 如果是radio控件
                    $.each(tagobjs, function(keyobj, value) {
                        if ($(value).attr("val") == jsonObj[key]) {
                            value.checked = true;
                        }
                    });
                    continue;
                }
                $("[name=" + key + "]", $form).val(jsonObj[key]);
            } else { // 其他的直接赋值
                $("[name=" + key + "]", $form).val(jsonObj[key]);
            }

        }
    }

    var setCkb = function(name, value) {
        // alert(name + " " + value);
        // $("[name=" + name + "][value=" + value + "]").attr("checked", "checked");
        // 不知为何找不到具体标签;
        $("[name=" + name + "][val=" + value + "]").attr("checked", "checked");
    }

    var fillckb = function(name, json) {
        var jsonObj = json;
        if (typeof json === 'string') {
            jsonObj = $.parseJSON(json);
        }
        var str = jsonObj[name];
        if (typeof str === "string") {
            var array = str.split(",");
            $.each(array, function(key, value) {
                setCkb(name, value);
            });
        }
    }

    var jsonObjType = function(obj) {
        if (typeof obj === "object") {
            var teststr = JSON.stringify(obj);
            if (teststr[0] == '{' && teststr[teststr.length - 1] == '}')
                return "class";
            if (teststr[0] == '[' && teststr[teststr.length - 1] == ']')
                return "array";
        }
        return typeof obj;
    }
    //表单回填EN
</script>
<div class="content-wrap">
    <div class="wrapper" style="bottom: 50px;">
        <ul class="nav nav-tabs">
            <li>
                <a href="#"  onclick="loadDiv('rigthCenterDiv','${ctx}/drug/drugExport/badForm')">报损出库</a>
            </li>
        </ul>
        <section class="panel panel-default">
            <div class="panel-body">
                <div class="col-lg-12">
                    <form:form id="inputForm" data-parsley-validate=""  modelAttribute="drugExportDetail"
                               onsubmit="return formSaveLoad('mainCenterDiv','inputForm','${ctx}/drug/drugExport/save','${ctx}/drug/drugExport/drugBadIndex');" method="post" class="form-horizontal">
                    <form:hidden path="id" id="stockId"/>
                    <div class="form-group">
                        <label class="col-sm-4 control-label">药品名称：</label>
                        <div class="col-sm-8">
                            <form:input path="infoId" id="infoId" htmlEscape="false" class="form-control" maxlength="64" type="hidden" />
                            <form:input path="drugName" id="drugName" htmlEscape="false" class="form-control"  maxlength="64" data-parsley-required="true"/>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-4 control-label">报损数量:</label>

                        <div class="col-sm-8">
                            <form:input  path="quantityBad" id="quantityBad" htmlEscape="false" class="form-control" maxlength="8" />
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-4 control-label">当前库存:</label>

                        <div class="col-sm-8">
                            <form:input path="quantity" id="stockNum" htmlEscape="false" class="form-control" maxlength="8" readonly="true" />
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-4 control-label">药品编码：</label>

                        <div class="col-sm-8">
                            <form:input path="drugCode" htmlEscape="false" class="form-control" maxlength="32" readonly="true" />
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-4 control-label">包装数量：</label>
                        <div class="col-sm-8">
                            <form:input path="packageNum" htmlEscape="false" class="form-control"  maxlength="8" readonly="true"/>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-4 control-label">包装规格：</label>
                        <div class="col-sm-8">
                            <form:input path="packageSpec" htmlEscape="false" class="form-control"  maxlength="20" readonly="true"/>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-4 control-label">包装单位：</label>
                        <div class="col-sm-8">
                            <form:input path="packageUnits" htmlEscape="false" class="form-control"  maxlength="2" readonly="true"/>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-4 control-label">最小规格：</label>
                        <div class="col-sm-8">
                            <form:input path="minSpec" htmlEscape="false" class="form-control"  maxlength="20" readonly="true"/>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-4 control-label">最小单位：</label>
                        <div class="col-sm-8">
                            <form:input path="minUnits" htmlEscape="false" class="form-control"  maxlength="2" readonly="true"/>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-4 control-label">厂家：</label>
                        <div class="col-sm-8"> <!--库存表没有厂家字段，为了在页面显示出来，借用updateBy字段-->
                            <form:input path="drugSupplierCata" id="supplierName" htmlEscape="false" class="form-control"  maxlength="64" readonly="true"/>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-4 control-label">进货价：</label>
                        <div class="col-sm-8">
                            <form:input path="purchasePrice" id="purchasePrice" htmlEscape="false" class="form-control" readonly="true"/>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-4 control-label">零售价：</label>
                        <div class="col-sm-8">
                            <form:input path="retailPrice" id="retailPrice" htmlEscape="false" class="form-control" readonly="true"/>
                        </div>
                    </div>
                    <%--<div class="form-group">--%>
                        <%--<label class="col-sm-4 control-label">折扣：</label>--%>
                        <%--<div class="col-sm-8">--%>
                            <%--<form:input path="discount" id="discount" htmlEscape="false" class="form-control" readonly="true"/>--%>
                        <%--</div>--%>
                    <%--</div>--%>
                    <div class="form-group">
                        <label class="col-sm-4 control-label">批号：</label>
                        <div class="col-sm-8">
                            <form:input path="batchNo" id="batchNo" htmlEscape="false" class="form-control"  maxlength="64" readonly="true"/>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-4 control-label">有效期：</label>
                        <div class="col-sm-8">
                            <input id="expireDate2" name="expireDate" htmlEscape="false" class="form-control Wdate" data-parsley-required="true" readonly="true"
                                    value='<fmt:formatDate value="${drugPrice.startDate}" pattern="yyyy-MM-dd HH:mm:ss"/>'/>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-4 control-label">对应入库单号：</label>
                        <div class="col-sm-8">
                            <form:input path="documentNo" id="importDocumentNo" htmlEscape="false" class="form-control"  maxlength="64" readonly="true"/>
                        </div>
                    </div>
                </div>
                <div class="form-group">
                    <div class="col-sm-offset-2 col-sm-10">
                        <input id="btnSubmit" class="btn btn-primary" type="submit" value="确 定" onclick="addrows()">&nbsp;
                        <input id="btnCancel" class="btn" type="button" value="关 闭" onclick="closeRight()"></div>
                </div>
                </form:form>
            </div>
        </section>
    </div>
</div>

<script>
    /*药品自动补全*/
    autoCompleteDrugPrice("drugName");
    function autoCompleteDrugPrice(inputId){
        var list = $("table tr").find("td:eq(0)");  //左侧table表格数据
        var dataList = [];
        if(list.length > 0){
            for(var i = 0; i < list.length; i++){
                var data = jQuery.parseJSON(list[i].innerText);
                dataList.push(data);
            }
        }

        var url="${ctx}/drug/drugExport/autoExportStock";
        autoComplete(inputId,url,
                function(data){
                    var rows = [];
                    for(var i=0; i<data.length; i++){
                        rows[rows.length] = {
                            data:data[i],
                            value:data[i].id,
                            result:data[i].drugInfo.drugDict.drugName
                        };
                    }
                    return rows;
                },function(data, i, max){
                    return data.drugInfo.drugDict.drugName+"|"+"|"+data.packageSpec+"|"+data.drugInfo.drugSupplierCata.supplierName+"|"+data.drugStock.quantity+data.packageUnits;
                },function(event,data,formatted){
                    console.log(data);
                    if(dataList != null && dataList != [] && typeof(dataList) != 'undefined' && dataList.length > 0){
                        for(var i = 0; i < dataList.length; i++){
                            if(dataList[i]['drugInfo.id'] == data.id && dataList[i].batchNo == data.drugStock.batchNo){
                                toastr.error('出库列表中该规格的药品已经存在,请重新选择出库药品!');
                                addExportItem();
                                return ;
                            }
                        }
                    }
                    $('#supplierName').attr('value', data.drugInfo.drugSupplierCata.supplierName);
                    $('#infoId').attr('value',data.id);
                    $('#drugCode').attr('value',data.drugInfo.drugDict.drugCode);
                    $('#packageSpec').attr('value',data.packageSpec);
                    $('#packageUnits').attr('value',data.packageUnits);
                    $('#minSpec').attr('value',data.minSpec);
                    $('#minUnits').attr('value',data.minUnits);
                    $('#packageNum').attr('value',data.packageNum);
                    $('#purchasePrice').attr('value',data.drugStock.purchasePrice);
                    $('#retailPrice').attr('value',data.drugPrice.retailPrice);
                    $('#discount').attr('value',data.drugStock.discount);
                    $('#batchNo').attr('value',data.drugStock.batchNo);
                    $('#stockId').attr('value',data.drugStock.id);
                    $('#expireDate2').attr('value',data.drugStock.expireDate);
                    $('#stockNum').attr('value',data.drugStock.quantity);
                    $('#importDocumentNo').attr('value',data.drugStock.documentNo);
                });
    }
    //关闭右侧添加药品明细页面
    function closeRight(){
        $("#drugBadExportRightDiv").attr("style","display: none");
        $("#drugBadExportDiv").attr("class","main-content col-lg-12");
        $("#drugBadExportDiv").show('normal');
    }
</script>